<template lang="pug">
  div
    video.video(
      autoplay
      controls
      v-for="item in videoList"
      :id="item.id"
      ref="videos"
      :height="videoHeight"
      :muted="item.muted"
      v-show="item.isAudio === false"
    )
    div(:style="{height:videoHeight}" v-show="!noVideo" ref="noVideo").no-video
    div.record-box
      video#record
</template>

<script>
  import * as io from 'socket.io-client'
  import * as RTCMultiConnection from 'rtcmulticonnection'
  import {socketURL} from '../config/global.toml'

  window.io = io
  export default {
    name: 'webrtc',
    props: {
      roomId: {
        type: String,
        default: 'public'
      },
      userInfo: {
        type: Object,
        default() {
          return {}
        }
      },
      videoHeight: {
        type: [Number, String],
        default: 160
      }
    },
    data() {
      return {
        rtcmConnection: null,
        socketURL: socketURL,
        personList: [],
        videoList: [],
        share: 'stop',
        newUserInfo: {},
        noVideo: false,
        img: '',
        streamId: null,
        allChunks: []
      }
    },
    mounted() {
      let that = this
      this.rtcmConnection = new RTCMultiConnection()
      this.rtcmConnection.socketURL = this.socketURL
      // 通过extra附带一些基本信息
      this.rtcmConnection.extra.userInfo = this.userInfo
      // 禁止自动创建元素
      this.rtcmConnection.autoCreateMediaElement = false
      // 两边通信需要一致
      this.rtcmConnection.socketMessageEvent = 'canvas-dashboard-demo'
      // 不需要打印log
      this.rtcmConnection.enableLogs = false
      this.rtcmConnection.mediaConstraints = {
        audio: true,
        video: false
      }
      // 链接的内容，这里有视频、音频和message
      this.rtcmConnection.session = {
        audio: true,
        video: true,
        data: true
      }
      this.rtcmConnection.onstream = event => {
        console.log('------event-----', event)
        console.log('------stream-----', event.stream.isAudio)
        if (!that.videoList.find(item => item.id === event.streamid)) {
          that.videoList.push({
            id: event.streamid,
            muted: false,
            isAudio: event.stream.isAudio,
            userInfo: event.extra.userInfo,
            stream: event.stream
          })
          that.videoList.forEach(item => {
            if (item.userInfo.id === that.userInfo.id) {
              item.muted = true
            }
          })
          if (event.stream.isAudio === false) {
            that.noVideo = true
          }
          setTimeout(() => {
            this.$refs.videos.find(audio => audio.id === event.streamid).srcObject = event.stream
          }, 500)
        }
        if (!that.personList.find(item => item.userInfo.id === event.extra.userInfo.id)) {
          that.personList.push({
            userInfo: event.extra.userInfo
          })
          that.$emit('join', that.personList)
          let joinMessage = {
            from: {
              userInfo: event.extra.userInfo
            },
            join: true,
            content: '加入了房间'
          }
          that.$emit('message', joinMessage, 'message')
        }
        console.log('this.videoList', this.videoList)
      }
      this.rtcmConnection.onstreamended = event => {
        let index = that.personList.findIndex(item => item.userInfo.id === event.extra.userInfo.id)
        if (index !== -1) {
          that.personList.splice(index, 1)
          that.$emit('join', that.personList)
        }
      }
      this.rtcmConnection.onmessage = event => {
        console.log('++++++event++++++', event)
        if (event.data.connectingMike) {
          that.$emit('message', event.data.connectingMike, 'connectingMike')
        } else if (event.data.disConnectingMike) {
          that.$emit('message', event.data.disConnectingMike, 'disConnectingMike')
        } else if (event.data.message) {
          that.$emit('message', event.data.message, 'message')
        } else if (event.data.imgMessage) {
          that.$emit('imgMessage', event.data.imgMessage, 'imgMessage')
        } else if (event.data.share) {
          that.$emit('onShare', event.data.share, event.data.stream, 'share')
        } else if (event.data.roomId) {
          that.$emit('stopLive', event.data.roomId)
        }
      }
    },
    methods: {
      // 创建直播间
      open() {
        this.rtcmConnection.open(this.roomId, (isRoomJoined, roomid, error) => {
          console.log(isRoomJoined, roomid, error)
        })
      },
      // 加入直播间
      join() {
        this.rtcmConnection.join(this.roomId, (isRoomJoined, roomid, error) => {
          console.log(isRoomJoined, roomid, error)
          if (!isRoomJoined) {
            this.$message({
              message: '您选择的患者未发起会诊',
              type: 'error'
            })
          }
        })
      },
      // 发送消息
      sendMessage(message) {
        this.rtcmConnection.send({message})
      },
      // 发送图片消息
      sendImg(imgMessage) {
        this.rtcmConnection.send({imgMessage})
      },
      // 离开直播间
      leave(roomId) {
        this.share = 'stop'
        this.videoList = []
        this.noVideo = false
        this.rtcmConnection.attachStreams.forEach(localStream => {
          console.log('localStream', localStream)
          localStream.stop()
        })
        this.rtcmConnection.send({roomId: roomId})
      },
      addStreamStopListener(stream, callback) {
        let streamEndedEvent = 'ended'
        if ('oninactive' in stream) {
          streamEndedEvent = 'inactive'
        }
        stream.addEventListener(
          streamEndedEvent,
          function () {
            callback()
            callback = function () {
            }
          },
          false
        )
      },
      // 获取媒体流
      onGettingSteam(stream) {
        console.log('------stream------', stream)
        console.log('------userInfo------', this.userInfo)
        this.streamId = stream.streamid
        this.rtcmConnection.addStream(stream)
        if (!this.videoList.find(item => item.userInfo.id === stream.streamid)) {
          this.videoList.push({
            id: stream.streamid,
            muted: false,
            isAudio: false,
            userInfo: {
              id: this.userInfo.id,
              name: this.userInfo.name,
              avatar: this.userInfo.avatar,
              role: this.userInfo.role,
              position: this.userInfo.position,
              hospital: this.userInfo.hospital
            }
          })
        }
        this.noVideo = true
        console.log('videoList', this.videoList)
        setTimeout(() => {
          this.$refs.videos.find(audio => audio.id === stream.streamid).srcObject = stream
        }, 100)
        let that = this

        this.addStreamStopListener(stream, function () {
          // that.rtcmConnection.removeStream(stream.streamid)
          that.videoList.forEach(item => {
            item.muted = true
          })
          that.videoList.map((item, index) => {
            if (item.id === stream.streamid) {
              that.videoList.splice(index, 1)
            }
          })
          that.noVideo = false
          that.share = 'stop'
          that.rtcmConnection.send({share: that.share, stream: stream})
          that.$emit('showBtn')
        })
      },
      getDisplayMediaError(error) {
        console.log('Media error: ' + JSON.stringify(error))
      },
      // 屏幕共享
      shareScreen() {
        let that = this
        if (navigator.getDisplayMedia || navigator.mediaDevices.getDisplayMedia) {
          if (navigator.mediaDevices.getDisplayMedia) {
            navigator.mediaDevices
              .getDisplayMedia({
                video: {
                  height: 1080,
                  width: 1920
                },
                audio: true
              })
              .then(stream => {
                that.onGettingSteam(stream)
                that.share = 'start'
                that.videoList.forEach(item => {
                  item.muted = false
                })
                that.rtcmConnection.send({share: this.share})
              }, that.getDisplayMediaError)
              .catch(that.getDisplayMediaError)
          } else if (navigator.getDisplayMedia) {
            navigator
              .getDisplayMedia({
                video: {
                  height: 1080,
                  width: 1920
                },
                audio: true
              })
              .then(stream => {
                that.onGettingSteam(stream)
                that.share = 'start'
                that.videoList.forEach(item => {
                  item.muted = false
                })
                that.rtcmConnection.send({share: this.share})
              }, that.getDisplayMediaError)
              .catch(that.getDisplayMediaError)
          }
        }
      },
      // 屏幕共享状态切换
      shareChange(message, stream) {
        console.log('message', message, stream)
        this.share = message
        if (this.share === 'start') {
          this.videoList.forEach(item => {
            item.muted = false
          })
        } else if (this.share === 'stop') {
          this.videoList.forEach((item, index) => {
            item.muted = true
            if (item.id === stream.streamid) {
              this.videoList.splice(index, 1)
            }
            this.noVideo = false
          })
        }
      }
    }
  }
</script>

<style scoped lang="stylus">
  .video
    display block
    max-width 100%
    margin 0 auto

  .no-video
    width 100%
    background-color #000

  .record-box
    display none

</style>
